//
//  CircleOptionView.m
//  FFoundation
//
//  Created by 新庭 on 2020/1/5.
//

#import "CircleOptionView.h"
#import "UIView+FView.h"

static CGFloat kDegreeHeight = 15;
@interface CircleOptionViewDegree : UIView

@property (nonatomic, weak) CircleOptionView *circleOption;

@end

@interface CircleOptionView () <UIGestureRecognizerDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *touchScroll;
@property (nonatomic, strong) CircleOptionViewDegree *degreeView;

@property (nonatomic, assign) CGFloat offsetAngle;

@end

@implementation CircleOptionView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareSubviews];
    }
    return self;
}

- (void)prepareSubviews {
    self.step = 10;
    self.degreeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
    self.degreeAngle = M_PI;
    self.layer.masksToBounds = YES;
    
    self.userInteractionEnabled = YES;
    [self addSubview:self.degreeView];
    [self.degreeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
    
    [self addSubview:self.touchScroll];
    [self.touchScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
}

- (void)layoutSubviews {
    CGFloat radius = self.jk_width / 2;
    self.touchScroll.contentSize = CGSizeMake([self offsetForAngle:self.degreeAngle] + self.jk_width, self.touchScroll.jk_height);
    self.layer.cornerRadius = radius;
    
    [super layoutSubviews];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    if (selectedIndex < 0 || selectedIndex >= self.items.count) return;
    
    CGFloat angle = [self angleForIndex:selectedIndex];
    CGFloat offsetX = [self offsetForAngle:angle];
    [self.touchScroll setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    
    [super setSelectedIndex:selectedIndex];
}

#pragma mark - Scroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat angle = [self angleAtOffset:scrollView.jk_contentOffsetX];
    self.degreeView.transform = CGAffineTransformMakeRotation(-angle);
    
    NSInteger index = [self indexForAngle:angle];
    if (index != self.selectedIndex) {
        super.selectedIndex = index;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self locateScrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self locateScrollView];
    }
}

#pragma mark - Action

#pragma mark - Private
- (void)drawDegree:(CGRect)rect inContext:(CGContextRef)context {
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, rect.size.width / 2, rect.size.height / 2);
    
    CGFloat angle = [self anglePerIndex];
    CGFloat textWidth = 0;
    for (NSInteger i = 0; i < self.items.count; i++) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, -rect.size.width / 2, -rect.size.height / 2);
        
        OptionItem *item = self.items[i];
        if (i % self.step == 0) {
            textWidth = [item.description sizeWithAttributes:nil].width;
            [item.description drawInRect:CGRectMake(rect.size.width / 2 - textWidth / 2, self.degreeInsets.top, textWidth, kDegreeHeight) withAttributes:nil];
        } else {
            CGPoint line[2] = {CGPointMake(rect.size.width / 2, self.degreeInsets.top), CGPointMake(rect.size.width / 2, self.degreeInsets.top + kDegreeHeight)};
            CGContextStrokeLineSegments(context, line, 2);
        }

        CGContextRestoreGState(context);
        CGContextRotateCTM(context, angle);
    }
    CGContextRestoreGState(context);
}

- (void)locateScrollView {
    CGFloat angle = [self angleAtOffset:self.touchScroll.jk_contentOffsetX];
    NSInteger index = [self indexForAngle:angle];
    CGFloat offset = [self offsetForAngle:[self angleForIndex:index]];
    [self.touchScroll setContentOffset:CGPointMake(offset, 0) animated:YES];
}

- (CGFloat)offsetForAngle:(CGFloat)angle {
    return (angle) * (self.jk_width / 2);
}

- (CGFloat)angleAtOffset:(CGFloat)offset {
    return offset / (self.jk_width / 2);
}

- (CGFloat)anglePerIndex {
    return self.degreeAngle / (self.items.count - 1);
}

- (CGFloat)angleForIndex:(NSInteger)index {
    return [self anglePerIndex] * index;
}

- (CGFloat)indexForAngle:(CGFloat)angle {
    CGFloat i = angle / [self anglePerIndex];
    return MIN(self.items.count - 1, MAX(0, round(i)));
}

- (CircleOptionViewDegree *)degreeView {
    if (!_degreeView) {
        _degreeView = [[CircleOptionViewDegree alloc] init];
        _degreeView.backgroundColor = [UIColor whiteColor];
        _degreeView.circleOption = self;
    }
    return _degreeView;
}

- (UIScrollView *)touchScroll {
    if (!_touchScroll) {
        _touchScroll = [[UIScrollView alloc] init];
        _touchScroll.scrollEnabled = YES;
        _touchScroll.delegate = self;
        _touchScroll.showsHorizontalScrollIndicator = NO;
        _touchScroll.bounces = NO;
    }
    return _touchScroll;
}

- (CGFloat)offsetAngle {
    return M_PI_2;
}

@end

@implementation CircleOptionViewDegree

- (void)drawRect:(CGRect)rect {
    [self.circleOption drawDegree:rect inContext:UIGraphicsGetCurrentContext()];
}

@end
